package com.uah;

import java.util.ArrayList;
import java.util.List;

import com.scraper.CalendarWebData;
import com.scraper.CalendarWebScraper;
import com.scraper.CourseListingWebData;
import com.scraper.CourseListingWebScraper;
import com.scraper.Link;
import com.scraper.ScraperType;
import com.scraper.WebReader;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TableLayout;

public class CurrentStudents extends Activity {
	Button tempButton;
	Spinner currentStudentsMenu;
	TableLayout page1TableLayout;
	BackgroundThread scraperThread;
	CalendarWebData calendarData;
	List<Link> courseListingsLinks;
	ProgressDialog progDialog;
	
	//Hardcoded External Links
	Link item1 = new Link("https://angel.uah.edu/", "Angel");
	  Link item2 =new Link("https://sierra.uah.edu:9021/PROD/twbkwbis.P_GenMenu?name=homepage", "Banner");
	  Link item3 =new Link("http://uah.bncollege.com", "Bookstore");
	  Link item4 =new Link("http://www.uah.edu/its/", "Helpdesk");
	  Link item5 =new Link("http://libguides.uah.edu/mobile/3855", "Library");
	
	Link[] externalLinks={item1, item2, item3, item4, item5};

	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
	    setContentView(R.layout.page1);
		
		scraperThread = new BackgroundThread();
		scraperThread.start();
	    
	    page1TableLayout = (TableLayout) findViewById(R.id.page1TableLayout);
	    page1TableLayout.removeAllViewsInLayout();
	    
	    currentStudentsMenu = (Spinner)findViewById(R.id.spinner1);
	    currentStudentsMenu.setOnItemSelectedListener(menuListener);
	    
	    if (scraperThread.isAlive())
		{
			progDialog = ProgressDialog.show(this, "Loading",
		            "....please wait....", true);	
		}
	}
    
	// Populate layout appropriately for each menu option
    private  OnItemSelectedListener menuListener = new OnItemSelectedListener(){
    	@Override
        public void onItemSelected(AdapterView<?> parent, View view, 
                int pos, long id) {    	
    		
    		page1TableLayout.removeAllViewsInLayout();
    		
    		//Wait for scraper data to be available
    		try {
      		   scraperThread.join();
      	    } catch (InterruptedException e) {
      	    
      	    }
            if (id == 0)		//Calendars
            {
            	populateCalendarPage();
            }
            else if (id == 1)	//Course Schedule
            {
            	populateCourseSchedule();
            }
            else if (id == 2)	//Course Search
            {
            	Intent myIntent = new Intent(view.getContext(), Search.class);
            	view.getContext().startActivity(myIntent);
            	
            }
            else if (id == 3)	//External Links
            {
            	parseExternalLinks(view);
            }
            else
            {

            }
        }

    	@Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    };
    
    //Go through each category of calendars and add links under correct title
	public void populateCalendarPage(){    	
		DynamicLayoutCreation.createNewRow("Current Year Calendars", page1TableLayout, this);
		for (Link calendar : calendarData.currentYearCalendars){
			DynamicLayoutCreation.createNewRow(calendar, "", page1TableLayout, this);
		}
		
		DynamicLayoutCreation.createNewRow("", page1TableLayout, this);
		DynamicLayoutCreation.createNewRow("Future Calendars", page1TableLayout, this);
		for (Link calendar : calendarData.futureCalendars){
			DynamicLayoutCreation.createNewRow(calendar, "", page1TableLayout, this);
		}
				
		DynamicLayoutCreation.createNewRow("", page1TableLayout, this);
		DynamicLayoutCreation.createNewRow("Previous Year Calendars", page1TableLayout, this);
		for (Link calendar : calendarData.previousYearCalendars){
			DynamicLayoutCreation.createNewRow(calendar, "", page1TableLayout, this);
		}
			
		DynamicLayoutCreation.createNewRow("", page1TableLayout, this);
		DynamicLayoutCreation.createNewRow("Archived Calendars", page1TableLayout, this);
		for (Link calendar : calendarData.archivedCalendars){
			DynamicLayoutCreation.createNewRow(calendar, "", page1TableLayout, this);
		}
    }
    
	// Add buttons for each semester's course listings
    public void populateCourseSchedule(){
    	for (Link courseListing : courseListingsLinks){
    		//Try to delete "Course Listing" from button
    		courseListing.description = courseListing.description.replace("Course Listing", "");
    		courseListing.description = courseListing.description.replace("COURSE LISTING", "");
    		courseListing.description = courseListing.description.replace("course listing", "");
    		DynamicLayoutCreation.createNewRow(courseListing, "page2::", page1TableLayout, this);
    	}
    }
    
    // Create a button for each external link
    public void parseExternalLinks(View view){ 	
    	for(Link extLink : externalLinks)
    	{
    		DynamicLayoutCreation.createNewRow(extLink, "", page1TableLayout, this);
    	}
    }
    
    /**
	 * This method is intended to show how to use the WebScraper classes to scrape the current course listings.
	 * 
	 * The steps are the following: 
	 * 1. Initialize a particular WebScraper and WebReader
	 * 2. Set the ScraperType on the WebScraper
	 * 3. Call the "scrapeWebPage" method from the WebReader
	 * 4. Retrieve the WebData object from the particular WebScraper
	 * 
	 * @param courseListingsUrl
	 */
    void scrapeCourseListing(String courseListingsUrl){
    	courseListingsLinks = new ArrayList<Link>();
    	
		// Initialize Scraper and Reader (Step 1)
		CourseListingWebScraper courseListingScraper = new CourseListingWebScraper();
		WebReader webReader = new WebReader(courseListingScraper); 
		
		// Scrape Current Course Listings; most recent available course listings
		courseListingScraper.scraperType = ScraperType.CurrentCourseListings; // (Step 2)
		webReader.scrapeWebPage(courseListingsUrl); // (Step 3)
		CourseListingWebData courseListingData = courseListingScraper.getScrapedData(); // (Step 4)
		courseListingsLinks = courseListingData.currentCourseListings;		
	}
    
    void scrapeCalendars(){
    	String calendarURL = "http://www.uah.edu/registrar/calendars"; 
		CalendarWebScraper calendarScraper = new CalendarWebScraper();
		calendarScraper.setScraperType(ScraperType.Calendar);
		WebReader webReader = new WebReader(calendarScraper);
		webReader.setScraper(calendarScraper);
		webReader.scrapeWebPage(calendarURL);
		calendarData = calendarScraper.getScrapedData(); 
	}
    
    public class BackgroundThread extends Thread
    {
    	
    	public void run() {  
    		android.os.Process.setThreadPriority
    		(android.os.Process.THREAD_PRIORITY_DEFAULT);

    		scrapeCalendars();
    		
    		String courseListingsUrl = "http://www.uah.edu/cgi-bin/schedule.pl";
    		scrapeCourseListing(courseListingsUrl);
    		
    		//Dismiss loading bar
    		if (progDialog.isShowing())
    			progDialog.dismiss();
    	}
    }
}
